import "../../Fastfile"

default_platform(:ios)


platform :ios do
  # Authenticate with Apple Store
  private_lane :authenticate_apple_store do
    app_store_connect_api_key(
      key_id: ENV["ASC_KEY_ID"],
      issuer_id: ENV["ASC_ISSUER_ID"],
      key_content: ENV["ASC_KEY_P8_BASE64"],
      is_key_content_base64: true,
      in_house: false
    )
  end

  # Build iOS app
  lane :build_ipa do |options|
    authenticate_apple_store
    
    build_flutter_app(
      type: "ipa",
      no_codesign: options[:no_codesign] || false,
      config_only: options[:config_only] || false,
      build_number: options[:build_number] || get_build_number('appstore'),
      version_number: options[:version_number] || get_version_from_pubspec(),
      store: "appstore"
    )
  end


  desc "Release a new build to Apple Store"
  lane :release_app_store do |options|
    verify_env(envs: [
      "ASC_KEY_ID",
      "ASC_ISSUER_ID",
      "ASC_KEY_P8_BASE64",
      "APP_BUNDLE_ID",
      "MATCH_PASSWORD",
      "MATCH_GIT_BASIC_AUTHORIZATION",
    ])

    authenticate_apple_store

    build_number = options.fetch(:build_number, get_build_number('appstore'))
    version_number = options.fetch(:version_number, get_version_from_pubspec())

    # Verify version number is correct
    if !is_ci && (!options[:version_number])
      continue = UI.confirm("Deploying version #{version_number} (from pubspec.yaml) to App Store. Continue?")

      unless continue
        UI.user_error!("Aborted")
      end
    end

    # Sync certificates and profiles using match
    UI.message("Syncing certificates and profiles")
    
    if is_ci
      UI.message("CI detected. Setting up CI environment")
      setup_ci
    end

    sync_code_signing(
      type: "appstore",
      readonly: is_ci,
    )

    build_ipa(
      build_number: build_number,
      version_number: version_number
    )

    build_app(
      skip_build_archive: true,
      archive_path: "../build/ios/archive/Runner.xcarchive",
    )

    # If GoogleService-Info.plist exists and Pods/FirebaseCrashlytics exists
    # Upload symbols to Firebase Crashlytics
    if File.file?("../ios/Runner/GoogleService-Info.plist") && File.directory?("../ios/Pods/FirebaseCrashlytics")
      upload_symbols_to_crashlytics(
        gsp_path: "../ios/Runner/GoogleService-Info.plist"
      )
    end

    upload_to_testflight(
      skip_waiting_for_build_processing: true
    )
  end
  
  # This is a work in progress, requiring ad-hoc export method
  # desc "Release to Play Store using Firebase App Distribution"
  # lane :release_to_firebase do |options|
  #   begin
  #     build_ipa

  #     firebase_app_distribution(
  #       app: ENV["FIREBASE_APP_ID"],
  #       service_credentials_file: google_service_account_json_path,
  #       ipa_path: "../build/ios/Runner.ipa"
  #     )
  #   end
  # end
end
